<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/6/6
 * Time: 下午2:26
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class OilCard extends Model
{
    protected $table = 'oil_card';

    protected $guarded = [];

    // 1中石化，2中石油
    const TYPE_ZSH = 1;
    const TYPE_ZSY = 2;

    public $appends = ['type_name'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function rechargeOrderDetail()
    {
        return $this->hasMany(RechargeOrderDetail::class);
    }

    public function getTypeNameAttribute()
    {
        if ($this->type == self::TYPE_ZSH) {
            return '中石化';
        }
        if ($this->type == self::TYPE_ZSY) {
            return '中石油';
        }
        return '未定义';
    }

    /**
     * 本月已充值金
     * @return mixed
     */
    public function getCurrentMonthRechargedAmount()
    {
        return $this->rechargeOrderDetail()
            ->whereYear('pay_at', date('Y'))
            ->whereMonth('pay_at', date('m'))
            ->where('is_paid', 1)
            ->sum('amount');
    }

    /**
     * 本月应充金额
     * @return mixed
     */
    public function getCurrentMonthAmount()
    {
        return $this->rechargeOrderDetail()
            ->whereYear('pay_at', date('Y'))
            ->whereMonth('pay_at', date('m'))
            ->sum('amount');
    }

    /**
     * 累计已充值金额
     * @return mixed
     */
    public function getTotalRechargedAmount()
    {
        return $this->rechargeOrderDetail()
            ->where('is_paid', 1)
            ->sum('amount');
    }
}